package org.review.datastructure;

import java.util.Scanner;

public class Queue {

    public static void main(String[] args) {
        Queue queue = new Queue(3);
        char key = ' '; //接收用户输入
        Scanner scanner = new Scanner(System.in);//
        boolean loop = true;
//输出一个菜单
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("g(get): 从队列取出数据");
            System.out.println("h(head): 查看队列头的数据");
            key = scanner.next().charAt(0);//接收一个字符
            switch (key) {
                case 's':
                    queue.showQue();
                    break;
                case 'a':
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();

                    queue.addElement(value);
                    break;
                case 'g': //取出数据
                    try {
                        int res = queue.getElement();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        // TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h': //查看队列头的数据
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                    // TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e': //退出
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
    }

    private int maxSize;
    private int[] queArray;
    private int front;
    private int rear;

    public Queue(int maxSize) {
        this.maxSize = maxSize;
        queArray = new int[maxSize];
    }

    public void showQue() {
        if (isEmpty()) throw  new RuntimeException("队列为空!");

        for (int i = 0; i < queArray.length; i++) {
            System.out.printf("queArray[%d] = %d\n", i, queArray[i]);
        }
    }

    public boolean isFull() {
        return rear == maxSize; // TODO: 2024/7/29  因为rear初始索引是0, 每次加完以后指向的是下一个位置
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public void addElement(int element) {
        if (isFull())throw new RuntimeException("队列已满");
        queArray[rear++] = element;
    }

    public int getElement() {
        if (isEmpty())throw new RuntimeException("队列为空!");
        return queArray[front++];
    }

    public int headQueue() {
        if (isEmpty())throw new RuntimeException("队列为空!");
        return queArray[front];
    }
}
